package com.wing.sell.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wing.product.model.entity.ProductDetail;
import com.wing.product.service.DynamicService;
import com.wing.product.service.ProductDetailService;
import com.wing.sell.dao.OrderProDao;
import com.wing.sell.model.entity.CustomerProductCatalog;
import com.wing.sell.model.entity.Order;
import com.wing.sell.model.entity.OrderPro;
import com.wing.sell.model.entity.OrderProReview;
import com.wing.sell.model.request.OrderProForm;
import com.wing.sell.model.response.FinishedOrderDetailVo;
import com.wing.sell.model.response.OrderProDetailVo;
import com.wing.sell.model.response.OrderProVO;
import com.wing.sell.model.response.OrderReviewNeedVo;
import com.wing.sell.service.CustomerProductCatalogService;
import com.wing.sell.service.OrderProReviewService;
import com.wing.sell.service.OrderProService;
import com.wing.sell.service.OrderService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * 销售订单产品表-ServiceImpl
 *
 * @author
 */
@Service
@Slf4j
public class OrderProServiceImpl extends ServiceImpl<OrderProDao, OrderPro> implements OrderProService {

    @Autowired
    private OrderProService orderProService;

    @Autowired
    private CustomerProductCatalogService catalogService;

    @Autowired
    private ProductDetailService productDetailService;

    @Autowired
    private OrderService orderService;

    @Autowired
    private DynamicService dynamicService;

    @Autowired
    private OrderProReviewService orderProReviewService;


    @Override
    public int add(OrderProForm orderProForm) {

        //校验

        OrderPro orderPro = new OrderPro();
        CopyOptions copyOptions = CopyOptions.create()
                .setEditable(OrderPro.class)
                .setIgnoreError(true)
                .setIgnoreNullValue(true);
        BeanUtil.copyProperties(orderProForm, orderPro, copyOptions);
        return baseMapper.insert(orderPro);
    }

    @Override
    public List<OrderProVO> list4app(Map<String, Object> params) {
        return baseMapper.list4app(params);
    }

    @Override
    public Page<OrderProVO> pageList4app(Page page, Map<String, Object> params) {
        List<OrderProVO> list = baseMapper.list4app(page, params);
        page.setRecords(list);
        return page;
    }

    @Override
    public OrderProVO get4appById(Long id) {
        return baseMapper.get4appById(id);
    }

    @Override
    public OrderPro getOrderProVOByOrderId(Long orderId, String skuCode) {
        LambdaQueryWrapper<OrderPro> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(OrderPro::getOrderId, orderId);
        wrapper.eq(OrderPro::getCustomerSkuItem, skuCode);
        return baseMapper.selectOne(wrapper);
    }

    /**
     * 查询询价中的基本信息
     *
     * @param orderId
     * @param proId
     * @return
     */
    @Override
    public OrderReviewNeedVo selectReviewNeedInfoBy(Long orderId, Long proId) {
        return baseMapper.selectReviewNeedInfoBy(orderId, proId);
    }

    /**
     * 查询未处理的订单数量
     *
     * @param orderId
     * @return
     */
    @Override
    public Integer getCountNotReviewCount(Long orderId) {
        return baseMapper.getCountNotReviewCount(orderId);
    }

    /**
     * 修改
     *
     * @param orderProForm
     * @return
     */
    @Override
    @Transactional
    public Boolean updateInfo(OrderProForm orderProForm) {
        OrderPro orderPro = orderProService.getById(orderProForm.getId());
        CopyOptions copyOptions = CopyOptions.create()
                .setEditable(OrderPro.class)
                .setIgnoreError(true)
                .setIgnoreNullValue(true);
        BeanUtil.copyProperties(orderProForm, orderPro, copyOptions);

        Order byId1 = orderService.getById(orderProForm.getOrderId());

        if (orderProForm.getOrderProReviewList() != null && orderProForm.getFinalResult() == null) {
            //添加评审环节  受理此产品  不是设置终审结果
            for (OrderProReview orderProReview : orderProForm.getOrderProReviewList()) {
                //查询catalog目录id
                QueryWrapper<CustomerProductCatalog> catalogQueryWrapper = new QueryWrapper<>();
                catalogQueryWrapper.eq("customer_id", orderProForm.getCustomerId());
                catalogQueryWrapper.eq("ext_product_id", orderProReview.getCusProductId());
                CustomerProductCatalog byId = catalogService.getOne(catalogQueryWrapper);
                //如果客户目录下的外部产品有没有绑定sku 则需要生成评任务
                if (null == byId.getInSkuCode()) {
                    //刚添加的评审环节状态未待评审
                    orderProReview.setStatus(OrderProReview.Status.pending);
                    orderProReview.setOrderId(orderProForm.getOrderId());
                    orderProReview.setProId(orderProReview.getCusProductId());
                    orderProReview.setReviewCatalogId(byId.getId());
                    //评审截止时间
                    orderProReview.setReviewEndTime(orderProReview.getReviewEndTime());
                    //评审岗位id
                    orderProReview.setReviewPostId(orderProReview.getReviewPostId());
                    orderProReview.setReviewPostName(orderProReview.getReviewProcessName());
                    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMdd");
                    String code = dynamicService.getDayNextCode("sel_order_pro_review");
                    String day = simpleDateFormat.format(new Date());
                    orderProReview.setCode("PS" + day + code);
                    orderProReview.setDay(Integer.valueOf(day));
                    orderProReview.setNo(Integer.valueOf(code));
                    orderProReviewService.save(orderProReview);
                } else {
                    //直接评审通过
                    ProductDetail product = productDetailService.getById(byId.getInSkuCode());
                    orderPro.setSuggestLowestPrice(product.getSuggestionMinPrice() == null ? null : product.getSuggestionMinPrice().toString());
                    orderPro.setSuggestPrice(product.getMinPrice() == null ? null : product.getMinPrice().toString());
                    orderPro.setFinalResult(OrderPro.FinalResult.pass);
                    orderPro.setProductDetailId(product.getId());
                    orderPro.setOfferStatus(OrderPro.OfferStatus.wait);
                }
            }
        }
        //不受理
        else{
            //把这个产品的最终结果改为不接单
            orderPro.setOfferStatus(OrderPro.OfferStatus.wait);
            orderPro.setFinalResult(OrderPro.FinalResult.fail);
            orderProService.updateById(orderPro);

            //查询这个订单有几个产品
            Integer count = orderProService.selectCountBy(orderProForm.getOrderId());
            if (count <= 1) {
                //直接关闭
                byId1.setStatus(Order.Status.over);
                byId1.setUpdateTime(LocalDateTime.now());
                orderService.updateById(byId1);
            }
        }

        orderProService.updateById(orderPro);

        Integer notDoIt = orderProService.getCountDoIt(orderProForm.getOrderId());
        if (notDoIt <= 0) {
            //设置为待评审
            byId1.setStatus(Order.Status.review);
            byId1.setUpdateTime(LocalDateTime.now());
            if (ObjectUtil.isNotEmpty(byId1)) {
                orderService.updateById(byId1);
            }
        }

        Integer notDoCount = orderProService.getCountNotReviewCount(orderProForm.getOrderId());
        if (notDoCount <= 0) {
            //设置为待报价
            byId1.setStatus(Order.Status.offer);
            byId1.setUpdateTime(LocalDateTime.now());
            if (ObjectUtil.isNotEmpty(byId1)) {
                orderService.updateById(byId1);
            }
        }

        return true;
    }

    /**
     * 查询订单中 未被处理的产品
     *
     * @param orderId
     * @return
     */

    @Override
    public Integer getCountDoIt(Long orderId) {
        return baseMapper.getCountDoIt(orderId);
    }

    /**
     * 查询订单下的产品数量
     *
     * @param orderId
     * @return
     */
    @Override
    public Integer selectCountBy(Long orderId) {
        return baseMapper.selectCountBy(orderId);
    }

    /**
     * 查询 没有绑定内部sku的产品
     * @param orderId
     * @return
     */
    @Override
    public List<OrderPro> listNotInnerInfo(Long orderId) {
        return this.baseMapper.listNotInnerInfo(orderId);
    }

    /**
     * 查询剩余和已排产
     * @param skuCode 物料id
     * @param orderId 订单id
     * @return
     */
    @Override
    public Map<String, Object> getNeedInfoBy(String skuCode, Long orderId) {
        return this.baseMapper.getNeedInfoBy(skuCode,orderId);
    }

    /**
     * 查询正式订单明细
     * @param pg
     * @param params
     * @return
     */
    @Override
    public IPage<OrderProDetailVo> pageListDetailBy(Page<OrderProDetailVo> pg, Map<String, Object> params) {
        List<OrderProDetailVo> list = baseMapper.pageListDetailBy(pg, params);
        pg.setRecords(list);
        return pg;
    }

    @Override
    public Integer getOrderProResidueQuantity(Long proId) {
        return baseMapper.getOrderProResidueQuantity(proId);
    }
}
